<template>
  <!-- 1. 添加专业 -->
  <el-button @click="addMajorHandler" type="primary">添加专业</el-button>
  <!-- 2. 展示专业（修改，删除） -->
  <el-table :data="majorListRef" style="margin: 20px 0">
    <el-table-column type="index" label="索引" width="100">
      <template #default="scope">
        {{ scope.$index + 1 + sizeRef * (nowPageRef - 1) }}
      </template>
    </el-table-column>
    <el-table-column label="专业名称" prop="majorname"></el-table-column>
    <el-table-column label="操作" prop="op" width="150">
      <template #default="scope">
        <el-button
          type="primary"
          size="small"
          @click="updateMajorHandler(scope.row)"
          >编辑</el-button
        >
        <el-popconfirm
          title="你确定要删除这一项？"
          @confirm="deleteMajor(scope.row._id)"
        >
          <template #reference>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 3. 翻页组件 -->
  <el-pagination
    v-model:current-page="nowPageRef"
    v-model:page-size="sizeRef"
    :page-sizes="[5, 10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalRef"
  ></el-pagination>

  <!--4. 弹窗组件 -->
  <el-dialog :title="titleRef" v-model="dialogRef" width="500" @close="close">
    <!-- 专业相关的表单数据 -->
    <el-form :model="majorForm" :rules="formRules" ref="formEle">
      <el-form-item label="专业名称" prop="majorname">
        <el-input v-model="majorForm.majorname"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="addOrUpdate">确定</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus"
import { useAddAndUpdateMajor } from "./useAddAndUpdateMajor"
import { useShowMajor } from "./useShowMajor"
import { reqDelMajor } from "@/api/reqMajor"

// composition API的优点 （响应式数据分离了）

const { majorListRef, totalRef, nowPageRef, sizeRef, changeRef } =
  useShowMajor()

const {
  titleRef,
  dialogRef,
  majorForm,
  formRules,
  formEle,
  addMajorHandler,
  addOrUpdate,
  updateMajorHandler,
  close,
} = useAddAndUpdateMajor(changeRef)

// 删除专业
const deleteMajor = async (majorId: string) => {
  // 发送请求
  const { status } = await reqDelMajor({ majorId })
  if (status === 0) {
    ElMessage.success("删除成功")
    changeRef.value = Symbol()
  }
}
</script>

<style></style>
